<template>
  <div>
    <!-- 全局工具栏 -->
    <div class="toolbar">
      <div class="dropdown">
        文件
        <div class="dropdown-content">
          <a href="javascript:void(0)" @click="triggerFileInput"
            >导入Excel文件</a
          >
        </div>
      </div>
      <div>开始</div>
    </div>
    <el-card class="box-card">
      <h3>说明：</h3>
      <div v-for="(o, idx) in example" :key="idx" class="text-item">
        {{ idx + 1 + "、" + o }}
      </div>
    </el-card>
    <!-- 表格容器 -->
    <div class="table-container">
      <div
        v-show="contextMenuVisible"
        :style="{
          top: contextMenuPosition.y + 'px',
          left: contextMenuPosition.x + 'px',
        }"
        class="context-menu"
      >
        <ul>
          <li @click="insertRow">插入一行</li>
          <li @click="deleteRow">删除当前行</li>
          <li @click="viewContent">预览单元格内容</li>
        </ul>
      </div>

      <table id="excel-table">
        <thead>
          <tr id="header-row">
            <th v-for="(col, index) in columns" :key="index">{{ col }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in rows" :key="row.id">
            <td
              v-for="(cell, colIndex) in row.cells"
              :key="colIndex"
              contenteditable
              @contextmenu="showContextMenu($event, rowIndex, colIndex)"
              @click="handleClick($event, rowIndex, colIndex)"
              @input="handleInput($event, rowIndex, colIndex)"
              @paste="handlePaste($event, rowIndex, colIndex)"
            >
              <template v-if="colIndex == 0 || colIndex == 5 || colIndex == 6">
                <div
                  v-show="selectedCell.row == rowIndex"
                  :ref="setTdRef(rowIndex, colIndex)"
                  v-html="cell.value"
                ></div>
                <div v-show="selectedCell.row != rowIndex"></div>
              </template>
              <template v-if="colIndex == 1 && selectedCell.row == rowIndex">
                <el-select
                  v-model="chapters[rowIndex]"
                  multiple
                  placeholder="请选择章节"
                  style="width: 160px; margin-top: 25px"
                >
                  <el-option
                    v-for="item in chapterList"
                    :key="item.chapterId"
                    :label="item.chapterName"
                    :value="item.chapterId"
                  />
                </el-select>
              </template>
              <template v-if="colIndex == 2 && selectedCell.row == rowIndex">
                <el-rate
                  style="margin-top: 25px"
                  v-model="difficultyLevel[rowIndex]"
                />
              </template>
              <template v-if="colIndex == 3 && selectedCell.row == rowIndex">
                <el-radio-group v-model="questionType[rowIndex]">
                  <el-radio
                    :label="item.key"
                    v-for="item in questionTypeList"
                    >{{ item.value }}</el-radio
                  >
                </el-radio-group>
              </template>
              <template v-if="colIndex == 4 && selectedCell.row == rowIndex">
                <!-- 判断题 -->
                <template v-if="questionType[rowIndex] == 0">
                  <el-radio-group
                    v-model="judges[rowIndex]"
                    :ref="setTdRef(rowIndex, colIndex)"
                  >
                    <el-radio :label="1">正确</el-radio>
                    <el-radio :label="0">错误</el-radio>
                  </el-radio-group>
                </template>
                <!-- 处理单选 -->
                <template v-if="questionType[rowIndex] == 1">
                  <div
                    :ref="setTdRef(rowIndex, colIndex)"
                    class="options-container"
                    v-for="(item, index) in radioQuestionItemList[rowIndex]"
                    :key="index"
                  >
                    <div class="option-item">
                      <span class="letter">{{ LETTER[index] }}、</span>
                      <el-input
                        placeholder="选项内容"
                        type="text"
                        v-model="item.title"
                        style="width: 90px; margin-right: 10px"
                      />
                      <el-button
                        size="small"
                        @click="
                          reduceQuestionItem(
                            rowIndex,
                            index,
                            questionType[rowIndex]
                          )
                        "
                        v-if="index != 0"
                      >
                        <slot
                          ><el-icon v-if="index != 0"><CloseBold /></el-icon>
                        </slot>
                      </el-button>
                      <el-button
                        size="small"
                        @click="
                          addQuestionItem(rowIndex, questionType[rowIndex])
                        "
                        v-if="index == 0"
                      >
                        <slot
                          ><el-icon><Select /></el-icon>
                        </slot>
                      </el-button>
                    </div>
                  </div>

                  <div>
                    <el-radio-group
                      v-model="radios[rowIndex]"
                      :ref="setTdRef(rowIndex, colIndex)"
                    >
                      <el-radio
                        :label="index"
                        v-for="(item, index) in radioQuestionItemList[rowIndex]"
                      >
                        {{ LETTER[index] }}
                      </el-radio>
                    </el-radio-group>
                  </div>
                </template>
                <!-- 处理多选 -->
                <template v-if="questionType[rowIndex] == 2">
                  <div
                    class="options-container"
                    v-for="(item, index) in checkBoxQuestionItemList[rowIndex]"
                    :key="index"
                    :ref="setTdRef(rowIndex, colIndex)"
                  >
                    <div class="option-item">
                      <span class="letter">{{ LETTER[index] }}、</span>
                      <el-input
                        placeholder="选项内容"
                        type="text"
                        v-model="item.title"
                        style="width: 90px; margin-right: 10px"
                      />
                      <el-button
                        size="small"
                        @click="
                          reduceQuestionItem(
                            rowIndex,
                            index,
                            questionType[rowIndex]
                          )
                        "
                        v-if="index != 0"
                      >
                        <slot
                          ><el-icon><CloseBold /></el-icon>
                        </slot>
                      </el-button>
                      <el-button
                        size="small"
                        @click="
                          addQuestionItem(rowIndex, questionType[rowIndex])
                        "
                        v-if="index == 0"
                      >
                        <slot
                          ><el-icon><Select /></el-icon>
                        </slot>
                      </el-button>
                    </div>
                  </div>

                  <el-checkbox-group v-model="checkBox[rowIndex]">
                    <el-checkbox
                      :label="index"
                      v-for="(item, index) in checkBoxQuestionItemList[
                        rowIndex
                      ]"
                    >
                      {{ LETTER[index] }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
              </template>

              <template v-if="colIndex == 7 && selectedCell.row == rowIndex">
                <el-input-number
                  v-model="sorts[rowIndex]"
                  :min="1"
                  :max="100000"
                  size="small"
                  style="margin-top: 25px"
                />
              </template>
            </td>
          </tr>
        </tbody>
      </table>
      <el-button
        type="primary"
        style="float: right; margin-top: 20px; margin-right: 20px"
        size="large"
        @click="checkCell"
        >批量录入
      </el-button>
    </div>
    <el-dialog v-model="dialogVisible" title="内容预览" fullscreen>
      <div v-html="markdownContent"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  ref,
  onMounted,
  onUnmounted,
  reactive,
  nextTick,
  computed,
} from "vue";
import { marked } from "marked";
import { ElMessageBox, ElMessage } from "element-plus";
import { LETTER, QUESTION_TYPE } from "@/utils/Constants.js";
import { v4 as uuidv4 } from "uuid";
// 定义表格数据和状态
const columns = ref([
  "标题",
  "章节名称",
  "难度",
  "问题类型",
  "问题选项",
  "问题描述",
  "问题分析",
  "排序",
]);
const questionTypeList = computed(() => {
  let questionTypeList = [];
  for (let key in QUESTION_TYPE) {
    questionTypeList.push({
      key: Number.parseInt(key),
      value: QUESTION_TYPE[key],
    });
  }
  return questionTypeList;
});
// 使用 reactive 创建响应式二维数组
const rows = reactive(
  Array(1)
    .fill(null)
    .map(() => ({
      id: uuidv4(),
      cells: Array(8).fill(""),
    }))
);
const chapters = ref([]);
// 右键菜单相关
const showMenu = ref(false);
const menuPosition = ref({ x: 0, y: 0 });
const selectedCell = ref({ row: null, col: null });
const markdownContent = ref();
const targetCell = ref(null); // 用于存储当前选中的单元格
const contextMenuVisible = ref(false); // 控制右键菜单显示与隐藏
const contextMenuPosition = ref({ x: 0, y: 0 }); // 记录右键菜单的位置
const dialogVisible = ref(false);
const difficultyLevel = ref([1]);
const questionType = ref([1]);
const sorts = ref([1]);
const judges = ref([0]);
const radios = ref([0]);
const checkBox = ref([[]]);

const radioQuestionItemList = reactive(
  Array.from({ length: 1 }, () =>
    Array.from({ length: 1 }, () => reactive({ title: "", sort: 1 }))
  )
);
const checkBoxQuestionItemList = reactive(
  Array.from({ length: 1 }, () =>
    Array.from({ length: 1 }, () => reactive({ title: "", sort: 1 }))
  )
);
const chapterList = ref([]);
const tdRefs = reactive(
  Array(1)
    .fill(null)
    .map(() => Array(8).fill()) // 使用 ref 确保每个单元格的响应性
);
const { proxy } = getCurrentInstance();
// 文件输入
const fileInput = ref(null);
const example = [
  "标题 直接输入问题标题（必填）",
  "章节名称 请输入已经存在的章节名称（必填）",
  "难度 直接输入阿拉伯数字如 1、2、3、4、5 总共5个星级（必填）",
  "问题类型 输入 判断题、单选题、多选题 输入中文（必填）",
  "问题选项 一行一个问题选项（必填，判断题不填）",
  "问题答案，判断题直接输入正确或者错误，选择题输入A,B,C，支持html标签（必填）",
  "问题描述直接输入，支持html标签（非必填）",
  "答案解析直接输入，支持html标签（必填）",
  "排序输入数字即可，在组卷时可以用到",
  "以下红色部分是示例，请参照示例录入，最后请删除示例数据，否则示例会导入",
];
const api = {
  importExamQuestion: "/examQuestion/importExamQuestions",
  importChapters: "/examQuestion/importChapters",
};
function getColumnLabel(index) {
  let label = "";
  while (index >= 0) {
    label = String.fromCharCode((index % 26) + 65) + label;
    index = Math.floor(index / 26) - 1;
  }
  return label;
}
const handleClick = (event, rowIndex, colIndex) => {
  selectedCell.value = { row: rowIndex, col: colIndex }; // 设置当前选中的单元格
};

const reduceQuestionItem = (rowIndex, index, type) => {
  if (type == 1) {
    radioQuestionItemList[rowIndex].splice(index, 1);
  } else {
    checkBoxQuestionItemList[rowIndex].splice(index, 1);
  }
};
const addQuestionItem = (rowIndex, type) => {
  if (type == 1) {
    if (radioQuestionItemList[rowIndex].length >= 10) {
      proxy.Message.success("最多可以添加10个选项");
      return;
    }
    radioQuestionItemList[rowIndex].push(
      reactive({
        title: "",
        sort: radioQuestionItemList[rowIndex].length + 1,
      })
    );
  } else {
    if (checkBoxQuestionItemList[rowIndex].length >= 10) {
      proxy.Message.success("最多可以添加10个选项");
      return;
    }
    checkBoxQuestionItemList[rowIndex].push(
      reactive({
        title: "",
        sort: checkBoxQuestionItemList[rowIndex].length + 1,
      })
    );
  }
};
const removeTagsWithRegex = (htmlString) => {
  return htmlString.replace(/<[^>]*>/g, "");
};
const checkCell = async () => {
  ElMessageBox.confirm("确定要批量导入题目，检查无误?", "Warning", {
    confirmButtonText: "是的",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = [];
      rows.forEach((row, rowIndex) => {
        let item = {};
        item.title = removeTagsWithRegex(row.cells[0]);
        if (chapters.value[rowIndex])
          item.chapterIds = chapters.value[rowIndex].join(",");
        item.difficultyLevel = difficultyLevel.value[rowIndex];
        item.type = questionType.value[rowIndex];
        if (item.type == 0) {
          item.answer = judges.value[rowIndex];
        } else if (item.type == 1) {
          item.answer = radios.value[rowIndex];
          item.questionItems = radioQuestionItemList[rowIndex];
        } else if (item.type == 2) {
          item.answer = checkBox.value[rowIndex].join(",");
          item.questionItems = checkBoxQuestionItemList[rowIndex];
        }
        item.question = row.cells[5];
        item.analysis = row.cells[6];
        item.sort = sorts.value[rowIndex];
        data.push(item);
      });
      let result = await proxy.Request({
        url: api.importExamQuestion,
        params: {
          data: JSON.stringify(data),
        },
        dataType: "json",
      });
      if (!result) {
        return;
      }
      let res = result.data;

      let arr = res.split(" ");
      proxy.Message.success(
        `批量添加成功${arr[0] == "" ? 0 : arr[0]}个、失败${
          arr[1] == "" ? 0 : arr[1]
        }个`
      );
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除成功！",
      });
    });
};

const viewContent = () => {
  const html = rows[selectedCell.value.row].cells[selectedCell.value.col];
  markdownContent.value = html;
  dialogVisible.value = true;
};

const setTdRef = (rowIndex, colIndex) => {
  return (el) => {
    if (el) {
      // 确保 el 是有效的
      tdRefs[rowIndex][colIndex] = el;
    }
  };
};

// 显示右键菜单
const showContextMenu = (event, rowIndex, colIndex) => {
  event.preventDefault(); // 阻止默认右键菜单
  // 设置右键菜单位置
  contextMenuPosition.value = { x: event.clientX, y: event.clientY };
  contextMenuVisible.value = true; // 显示右键菜单
  selectedCell.value = { row: rowIndex, col: colIndex }; // 设置当前选中的单元格
};
// 隐藏右键菜单
const hideContextMenu = () => {
  contextMenuVisible.value = false;
};
const handleOptionPaste = (event, rowIndex) => {
  const clipboardData = event.clipboardData || window.clipboardData;
  const text = clipboardData.getData("text/plain");

  // 分割粘贴内容（按换行或逗号分割）
  const options = text.split(/\n|,/).filter((item) => item.trim());

  // 根据当前题目类型更新选项列表
  const type = questionType.value[rowIndex];
  if (type === 1) {
    // 单选题：覆盖原有选项
    radioQuestionItemList[rowIndex] = options.map((title, index) => ({
      title: title.trim(),
      sort: index + 1,
    }));
  } else if (type === 2) {
    // 多选题：覆盖原有选项
    checkBoxQuestionItemList[rowIndex] = options.map((title, index) => ({
      title: title.trim(),
      sort: index + 1,
    }));
  }

  // 同步答案选择（如单选默认选第一个）
  if (type === 1 && options.length > 0) {
    radios.value[rowIndex] = 0; // 选中第一个选项
  }
};
const handlePaste = (event, rowIndex, colIndex) => {
  if (colIndex === 4) {
    handleOptionPase(event, rowIndex);
    return;
  }
  // 阻止默认的粘贴处理
  event.preventDefault();

  // 获取ref引用
  const cell = tdRefs[rowIndex][colIndex];

  // 获取粘贴内容
  const clipboardData = event.clipboardData || window.clipboardData;
  const items = clipboardData.items;

  // 用于存储当前粘贴内容的对象
  let cellContent = "";

  // 查找粘贴内容中的图片、文本和 HTML
  for (let i = 0; i < items.length; i++) {
    const item = items[i];

    // 如果粘贴内容是图片
    if (item.type.indexOf("image") !== -1) {
      const file = item.getAsFile();
      const reader = new FileReader();

      reader.onload = (e) => {
        const imgElement = document.createElement("img");
        imgElement.src = e.target.result; // 设置图片的 base64 URL
        cell.appendChild(imgElement); // 将图片添加到对应的单元格

        // 将图片的 base64 URL 存储到 HTML 字符串中
        cellContent += `<img src="${imgElement.src}" />`;
        rows[rowIndex].cells[colIndex] += cellContent; // 更新数组中的值
      };
      reader.readAsDataURL(file); // 读取图片为 base64 格式
    }

    // 如果粘贴的内容是 HTML
    if (item.type === "text/html") {
      item.getAsString((html) => {
        const div = document.createElement("div");
        div.innerHTML = html; // 处理粘贴的 HTML
        cell.appendChild(div); // 将 HTML 添加到目标单元格

        // 将 HTML 内容存储到 HTML 字符串中
        cellContent += div.innerHTML;
        rows[rowIndex].cells[colIndex] += cellContent; // 更新数组中的值
      });
    }

    // 如果粘贴的是 Markdown
    else if (item.type === "text/plain") {
      item.getAsString((text) => {
        // 如果是 Markdown 格式的文本
        if (isMarkdown(text)) {
          // 将 Markdown 转换为 HTML
          const html = marked.parse(text);

          const div = document.createElement("div");
          div.innerHTML = html; // 将转换后的 HTML 内容插入到单元格中
          cell.appendChild(div); // 将 HTML 添加到目标单元格

          // 将 HTML 内容存储到 HTML 字符串中
          cellContent += div.innerHTML;
          rows[rowIndex].cells[colIndex] += cellContent; // 更新数组中的值
        } else {
          const textNode = document.createElement("span");
          textNode.textContent = text;
          cell.appendChild(textNode); // 将文本添加到目标单元格

          // 将文本内容存储到 HTML 字符串中
          cellContent += `<span>${text}</span>`;
          rows[rowIndex].cells[colIndex] += cellContent; // 更新数组中的值
        }
      });
    }
  }
};

// 检查文本是否是 Markdown 格式
const isMarkdown = (text) => {
  // 简单判断 Markdown 格式，可以根据需要更改逻辑
  return text.includes("#") || text.includes("**") || text.includes("*");
};

const handleInput = (event, rowIndex, colIndex) => {
  const inputValue = event.target.innerText;
  const htmlContent = marked.parse(inputValue);
  rows[rowIndex].cells[colIndex] = htmlContent;
};

// 在页面上点击时隐藏右键菜单
onMounted(async () => {
  document.addEventListener("click", hideContextMenu);
  const res = await proxy.Request({
    url: api.importChapters,
  });
  chapterList.value = res.data;
});

onUnmounted(() => {
  document.removeEventListener("click", hideContextMenu); // 清除事件监听器，防止内存泄漏
});
// 插入行

function insertRow() {
  rows.push({
    id: uuidv4(),
    cells: Array(8).fill(""),
  });
  tdRefs.push(Array(columns.value.length).fill(""));
  difficultyLevel.value.push(1);
  questionType.value.push(0);
  judges.value.push(0);
  radios.value.push(0);
  checkBox.value.push([]);
  chapters.value.push([]);
  sorts.value.push(1);
  // 创建新行（响应式对象）
  const newRow1 = Array.from({ length: 1 }, () =>
    reactive({ title: "", sort: 1 })
  );
  const newRow2 = Array.from({ length: 1 }, () =>
    reactive({ title: "", sort: 1 })
  );
  // 推送到数组末尾
  radioQuestionItemList.push(newRow1);
  checkBoxQuestionItemList.push(newRow2);
}

// 删除行
function deleteRow() {
  if (selectedCell.value.row !== null && rows.length > 1) {
    rows.splice(selectedCell.value.row, 1);
    tdRefs.splice(selectedCell.value.row, 1);
    difficultyLevel.value.splice(selectedCell.value.row, 1);
    questionType.value.splice(selectedCell.value.row, 1);
    judges.value.splice(selectedCell.value.row, 1);
    radios.value.splice(selectedCell.value.row, 1);
    checkBox.value.splice(selectedCell.value.row, 1);
    radioQuestionItemList.splice(selectedCell.value.row, 1);
    checkBoxQuestionItemList.splice(selectedCell.value.row, 1);
    sorts.value.splice(selectedCell.value.row, 1);
  } else {
    alert("至少要保留一行！");
  }
}

// 插入Markdown
function insertMarkdown() {
  isMarkdownEditorVisible.value = true;
}

// 显示文件上传对话框
function triggerFileInput() {
  fileInput.value.click();
}

// 点击页面其他地方关闭右键菜单
// document.addEventListener("click", closeContextMenu);
</script>

<style lang="scss" scoped>
body {
  margin: 0;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  overflow: hidden;
}

/* 全局工具栏样式 */
.toolbar {
  display: flex;
  background-color: #f2f2f2;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 10px;
}

.toolbar div {
  margin-right: 20px;
  cursor: pointer;
  font-weight: bold;
  color: #333;
  transition: color 0.3s ease;
}
.text-item {
  color: red;
  font-weight: 500;
}

.toolbar div:hover {
  color: #0078d7;
}

/* 下拉菜单 */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f2f2f2;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  border: 1px solid #ccc;
}

.dropdown-content a {
  padding: 8px 16px;
  display: block;
  text-decoration: none;
  color: #333;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

/* 表格容器 */
.table-container {
  margin: 20px;
  background: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  height: calc(100vh - 80px);
  overflow: auto;
}

/* 表格样式 */
table {
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed; /* 固定布局，列宽由 th/td 的宽度决定 */
}

th,
td {
  border: 1px solid #ddd;
  text-align: center;
  padding: 8px;
  cursor: pointer;
  user-select: none;
  white-space: normal; /* 禁止换行 */
  word-wrap: break-word;
  height: 50px;
  word-break: break-all;
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  vertical-align: top;
  overflow-x: auto; /* 水平滚动条 */
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
  height: auto;
  position: relative; /* 用于列宽拖动 */
}

/* 列宽拖动条 */
th::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  width: 5px;
  height: 100%;
  cursor: col-resize;
  background-color: transparent;
}

/* 自定义右键菜单 */
.context-menu {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.context-menu ul {
  list-style: none;
  margin: 0;
  padding: 5px 0;
}

.context-menu li {
  padding: 8px 15px;
  cursor: pointer;
  font-size: 14px;
}

.cell-center {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 40%; /* 确保高度撑满单元格 */
}

.context-menu li:hover {
  background-color: #f2f2f2;
}

/* 富文本编辑框 */
.markdown-editor {
  display: none;
  position: fixed;
  top: 20%;
  left: 50%;
  transform: translateX(-50%);
  background-color: white;
  padding: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  width: 400px;
  height: 300px;
  z-index: 1001;
  overflow-y: auto;
}

.markdown-editor textarea {
  width: 100%;
  height: 80%;
  border: 1px solid #ddd;
  padding: 10px;
  font-size: 16px;
  resize: none;
}

.markdown-editor button {
  width: 100%;
  padding: 10px;
  margin-top: 10px;
  background-color: #0078d7;
  color: white;
  border: none;
  cursor: pointer;
}

.markdown-editor button:hover {
  background-color: #005fa3;
}

.question-item {
  width: 100%;
  display: flex;
  .letter {
    width: 30px;
  }
  .title {
    flex: 1;
    .el-form-item {
      margin-bottom: 18px;
    }
  }
  .op {
    width: 100px;
    overflow: hidden;
    .iconfont {
      margin: 0px 10px;
      cursor: pointer;
    }
  }
}
</style>
